import { ref, reactive, nextTick, onMounted } from "vue";
import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance } from "element-plus";
import { useRoute } from "vue-router";
import {
  PersonGetAllByPagedAndSort,
  EnterpriseCreditResultDGaeeilstt,
  PersonalCreditModelGetAllByPagedAndSort,
  PersonalCreditModelShowPerSonTreeNodeInfo,
  PersonalCreditModelGetPersonalCreditModelNames,
  PersonalCreditScoreMeasurementGetAll,
  PersonalCreditScoreMeasurementGetAllByPagedAndSort,
  PersonalCreditScoreMeasurementCalculatePersonalCredit
} from "@/api/stu/DataScene";
import qs from "qs";

export function IndividualMarket() {
  // 信用数据
  const route = useRoute()
  const dataList = ref<any>();
  const loading = ref<boolean>(true);
  const keepmodel = ref(null);
  const ScoreParticulars_ = ref();
  const ModeDetails_ = ref();
  const REFModeDetails_ = ref();
  const tabsmodel = ref('1');
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "姓名",
      prop: "name",
      minWidth: 150
    }, {
      label: "性别",
      prop: "gender",
      minWidth: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.gender ? "warning" : "primary"}>
          {
            row.gender ? "女" : "男"
          }
        </el-tag>
      )
    }, {
      label: "年龄",
      prop: "age",
      minWidth: 100
    },
    {
      label: "民族",
      prop: "nation",
      minWidth: 100
    },
    {
      label: "身份证号码",
      prop: "idCard",
      minWidth: 200,
      cellRenderer: ({ row }) => (<span>{
        row.idCard.replace(/(\d{14})(\d{4})$/, "$1****")
      }</span>)
    },
    {
      label: "电话号码",
      prop: "phone",
      minWidth: 150,
      cellRenderer: ({ row }) => (<span>{
        row.phone.replace(/(\d{7})(\d{4})$/, "$1****")
      }</span>)
    },
    {
      label: "电子邮箱",
      prop: "email",
      minWidth: 150
    },
    {
      label: "婚姻状况",
      prop: "marriage",
      minWidth: 100
    },
    {
      label: "省份",
      prop: "province",
      minWidth: 200
    },
    {
      label: "家庭地址",
      prop: "homeAddress",
      minWidth: 200
    },
    {
      label: "职业",
      prop: "job",
      minWidth: 200
    },
  ]
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });

  // 评分模型列表
  const dataList2 = ref<any>();
  const loading2 = ref<boolean>(false);
  const columns2: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "模型名称",
      prop: "modelName",
      minWidth: 150
    },
    // {
    //   label: "创建时间",
    //   prop: "createTime",
    //   minWidth: 150
    // },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ]
  // 分页
  const pagination2 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });

  // 查看详情
  async function ShowDetails(row) {

    const res = await PersonalCreditModelShowPerSonTreeNodeInfo(qs.stringify({ enterpriseCreditModelId: row.personalCreditModelId }))
    if (res.success) {
      ModeDetails_.value = {
        data: res.data,
        type: "1"
      };
      REFModeDetails_.value.ModeVisible = true;
    } else {
      ElMessage.error(res.msg)
    }
  }

  // 新建评分模型
  function NewScoringModel() {
    // console.log("newmode.value", keepmodel.value)
    keepmodel.value.SetModeVisible();
  }

  // 信用分测算
  // 测算数据 列表
  const PersonModelName = ref([]) // 模型名称
  const PersonMyName = ref([])//申请测算个人名称
  // 测算数据 -- 选中的数据
  const PersonFrom = reactive<any>({
    modelId: "", // 模型名称
    personalId: "", // 申请测算个人名称
  })
  const dataList3 = ref<any>();
  const loading3 = ref<boolean>(false);
  const columns3: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    }, {
      label: "姓名",
      prop: "personName",
      minWidth: 150
    },
    {
      label: "身份证号码",
      prop: "idCard",
      minWidth: 200,
      cellRenderer: ({ row }) => (<span>{
        row.idCard.replace(/(\d{14})(\d{4})$/, "$1****")
      }</span>)
    },
    {
      label: "测试模型",
      prop: "modelName",
      minWidth: 150
    },
    {
      label: "信用分",
      prop: "creditScore",
      minWidth: 100
    },
    {
      label: "信用等级",
      prop: "creditRating",
      minWidth: 200,
      cellRenderer: ({ row }) => (
        <span>
          {
            row.creditRating === "1" ? "较差" :
              row.creditRating === "2" ? "中等" :
                row.creditRating === "3" ? "良好" :
                  row.creditRating === "4" ? "优秀" :
                    row.creditRating === "5" ? "极好" : ""
          }
        </span>
      )
    }, {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ]
  // 分页
  const pagination3 = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });

  // 查看详情 -- 测算后数据
  async function ShowDetails3(row) {
    const data = qs.stringify({
      modelId: row.personalCreditModelId,
      enterpriseId: row.pcsmId
    })
    const res = await EnterpriseCreditResultDGaeeilstt(data);
    if (res.success) {
      const data = {
        data: res.data,
        grade: row.creditRating === "1" ? "较差" :
          row.creditRating === "2" ? "中等" :
            row.creditRating === "3" ? "良好" :
              row.creditRating === "4" ? "优秀" :
                row.creditRating === "5" ? "极好" : "无",
        score: row.creditScore
      }
      ScoreParticulars_.value.ViewScore(data);
    } else {
      ElMessage.error(res.msg);
    }
  }

  async function ChangeCalculate() {
    if (PersonFrom.personalId == "" || PersonFrom.modelId == "") {
      ElMessage.warning("请输入个人名称和模型名称");
      return;
    }
    const data = {
      modelId: PersonFrom.modelId.personalCreditModelId,
      modelName: PersonFrom.modelId.modelName,
      personalId: PersonFrom.personalId.personalcreditreportId,
      personalName: PersonFrom.personalId.personaName,
      planId: route.query.planId,
      taskId: route.query.taskId
    };
    const res = await PersonalCreditScoreMeasurementCalculatePersonalCredit(data);
    if (res.success) {
      GetAllByPagedAndSort()
      ElMessage.success(res.msg);
    } else {
      ElMessage.error(res.msg);
    }
  }

  // 切换标签页
  function HandTabClick({ props }) {
    // console.log("tabls", props)
    if (props.name == "2") {
      GetMySortsList()
    }
    if (props.name == "3") {
      GetAllByPagedAndSort()
      GetPersonModelNameList()
    }
  }

  //////////

  function handleSizeChange(val) {
    // console.log("handleSizeChange", val)
    GetMarketCreditData()
  }

  function handleCurrentChange(val) {
    GetMarketCreditData()
    // console.log("handleCurrentChange", val)
  }



  function handleSizeChange2(val) {
    // console.log("handleSizeChange", val)
    GetPersonModelNameList()
  }

  function handleCurrentChange2(val) {
    GetPersonModelNameList()
    // console.log("handleCurrentChange", val)
  }

  function handleSizeChange3(val) {
    // console.log("handleSizeChange", val)
    GetAllByPagedAndSort()
  }

  function handleCurrentChange3(val) {
    GetAllByPagedAndSort()
    // console.log("handleCurrentChange", val)
  }


  // 获取个人呢市场化信用数据
  async function GetMarketCreditData() {
    const res = await PersonGetAllByPagedAndSort({
      planId: route.query.planId,
      taskId: route.query.taskId,
      "pageIndex": pagination.currentPage,
      "pageCount": pagination.pageSize
    });
    if (res.success) {
      pagination.total = res.data.totalCount;
      dataList.value = res.data.items;
      loading.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false }, 1500)
    }
  }

  // 获取 个人评分模型列表
  async function GetMySortsList() {
    const res = await PersonalCreditModelGetAllByPagedAndSort({
      planId: route.query.planId,
      taskId: route.query.taskId,
      "pageIndex": pagination2.currentPage,
      "pageCount": pagination2.pageSize
    });
    if (res.success) {
      pagination2.total = res.data.totalCount;
      dataList2.value = res.data.items;
      loading2.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading2.value = false }, 1500)
    }
  }

  // 获取测算个人名称数据列表
  async function GetPersonMyNameList() {
    const data = qs.stringify({
      planId: route.query.planId,
      taskId: route.query.taskId,
    })
    const res = await PersonalCreditScoreMeasurementGetAll(data);
    if (res.success) {
      PersonMyName.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  }

  // 获取测算模型名称数据列表
  async function GetPersonModelNameList() {
    const data = qs.stringify({
      planId: route.query.planId,
      taskId: route.query.taskId,
    })
    const res = await PersonalCreditModelGetPersonalCreditModelNames(data);
    if (res.success) {
      PersonModelName.value = res.data.items;
    } else {
      ElMessage.error(res.msg);
    }
  }

  // 获取测算列表数据
  async function GetAllByPagedAndSort() {
    const res = await PersonalCreditScoreMeasurementGetAllByPagedAndSort({
      planId: route.query.planId,
      taskId: route.query.taskId,
      "pageIndex": pagination3.currentPage,
      "pageCount": pagination3.pageSize
    });
    if (res.success) {
      pagination3.total = res.data.totalCount;
      dataList3.value = res.data.items;
      loading3.value = false
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading3.value = false }, 1500)
    }
  }

  onMounted(() => {
    GetMySortsList()
    GetPersonMyNameList()
    GetMarketCreditData()
    GetPersonModelNameList()
    GetAllByPagedAndSort()
  })


  return {
    dataList,
    loading,
    columns,
    tabsmodel,
    pagination,
    dataList2,
    loading2,
    columns2,
    pagination2,
    dataList3,
    loading3,
    columns3,
    keepmodel,
    pagination3,
    PersonModelName,
    PersonMyName,
    PersonFrom,
    ModeDetails_,
    REFModeDetails_,
    ScoreParticulars_,
    GetMySortsList,
    ShowDetails,
    ShowDetails3,
    HandTabClick,
    NewScoringModel,
    ChangeCalculate,
    handleSizeChange,
    handleCurrentChange,
    handleSizeChange2,
    handleCurrentChange2,
    handleSizeChange3,
    handleCurrentChange3,
    GetMarketCreditData
  }
}
